package com.easydisk.user.filter;

import com.easydisk.constant.CommonConstant;
import com.easydisk.user.config.RedisServer;
import com.easydisk.user.dao.RoleMapper;
import com.easydisk.user.dao.UserMapper;
import com.easydisk.user.model.entity.User;
import com.easydisk.user.pojo.LoginUser;
import com.easydisk.common.util.JwtUtil;
import com.easydisk.common.util.UserIdUtil;
import com.easydisk.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token=request.getHeader("Authorization");
        if(StringUtils.isEmpty(token)){
            //不需要token的路由可以直接放行
            filterChain.doFilter(request,response);
            return;
        }
        Long userId = null;
        try {
            //解析token
           Object obj= JwtUtil.analyzeToken(token, CommonConstant.LOGIN_USER_ID);
           userId = Long.valueOf(String.valueOf(obj));
        }catch (Exception e){
            throw new RuntimeException("token非法");
        }
        UserIdUtil.set(userId);
        User byId = userService.getById(userId);
        //生成authentication对象
       UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(byId.getUsername(),byId.getPassword(), null);
        //将信息存放到上下文中
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行
        filterChain.doFilter(request,response);
    }
}
